<?php 
require "global.php";

session_start();
    
$token_url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&"
        . "client_id=".$QQ_APPID."&redirect_uri=" . urlencode($QQ_OAUTH2_CALLBACK_URL)
        . "&client_secret=".$QQ_APPKEY."&code=" . $_REQUEST["code"];

$response = file_get_contents($token_url);
if (strpos($response, "callback") !== false)
{
    $lpos = strpos($response, "(");
    $rpos = strrpos($response, ")");
    $response  = substr($response, $lpos + 1, $rpos - $lpos -1);
    $msg = json_decode($response);
    if (isset($msg->error))
    {
        echo "<h3>error:</h3>" . $msg->error;
        echo "<h3>msg  :</h3>" . $msg->error_description;
        exit;
    }
}

$params = array();
parse_str($response, $params);

//debug
//print_r($params);

//set access token to session
$_SESSION["access_token"] = $params["access_token"];


$graph_url = "https://graph.qq.com/oauth2.0/me?access_token=" 
    . $_SESSION['access_token'];

$str  = file_get_contents($graph_url);
if (strpos($str, "callback") !== false)
{
    $lpos = strpos($str, "(");
    $rpos = strrpos($str, ")");
    $str  = substr($str, $lpos + 1, $rpos - $lpos -1);
}

$user = json_decode($str);
if (isset($user->error))
{
    echo "<h3>error:</h3>" . $user->error;
    echo "<h3>msg  :</h3>" . $user->error_description;
    exit;
}

//debug
//echo("Hello " . $user->openid);

//set openid to session
$_SESSION["openid"] = $user->openid;

$get_user_info = "https://graph.qq.com/user/get_user_info?"
    . "access_token=" . $_SESSION['access_token']
    . "&oauth_consumer_key=".$QQ_APPID
    . "&openid=" . $_SESSION["openid"]
    . "&format=json";

$info = file_get_contents($get_user_info);
$arr = json_decode($info, true);

//var_dump($arr);
//$_SESSION["QQUSERINFO"] = $arr;


//  得到登录前的页面
$currentPageURL = $_SESSION['currentPageURL'];

//var_dump($arr);
//  登录成功后把用户信息保存到session
$data['wbusername'] = $arr['nickname'];  //昵称
$data['wbuserheadpic'] = $arr['figureurl'];  // 头像
$data['wbuserwebsite'] = $currentPageURL;//  url  无法获取到qq用户的首页（没有），暂时使用登录时候的页面作为
$_SESSION['WEIBOUSERINFO'] = $data;

//echo "===============".$currentPageURL."<br>";
//  去掉URL上的code，安全考虑
//$arr = explode('&code=', $pageURL); 
//header("Location:$arr[0]");

header("Location:$currentPageURL");  // 跳转回到登录时候的页面


//print_r($_SESSION);
//echo "<script>window.close();</script>";
?>
